package com.dayaokeji.rhythmschoolstudent.client.common.questions_and_answers;


import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseFragment;
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.domain.FileInfo;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 全部问答
 */
public class AllAnswersFragment extends BaseFragment {

    private static final int FILE_STORE_PERMISSION_REQUEST_CODE = 10002;

    @BindView(R.id.rv_question_answers_list)
    RecyclerView rvQuestionAnswersList;

    private QuestionAndAnswersAdapter questionAndAnswersAdapter = new QuestionAndAnswersAdapter();
    private static final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private Call<ResponseBody> downloadCall;

    public static AllAnswersFragment newInstance() {
        
        Bundle args = new Bundle();
        
        AllAnswersFragment fragment = new AllAnswersFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public void setData(List<FileInfo> fileInfos){
        if (questionAndAnswersAdapter != null) {
            questionAndAnswersAdapter.setNewData(fileInfos);
        }
    }


    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_all_answers, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        checkStorePermission();
        setRecyclerView();
    }

    private void setRecyclerView() {
        questionAndAnswersAdapter = new QuestionAndAnswersAdapter();
        rvQuestionAnswersList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvQuestionAnswersList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .colorResId(R.color.color_default_divider)
                .sizeResId(R.dimen.default_divider_height)
                .build());
        rvQuestionAnswersList.setAdapter(questionAndAnswersAdapter);
        questionAndAnswersAdapter.setEmptyView(R.layout.empty_layout,rvQuestionAnswersList);

        questionAndAnswersAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List data = adapter.getData();
                int size = data.size();
                if (position < size) {
                    FileInfo fileInfo = (FileInfo) data.get(position);
                    if (AndPermission.hasPermissions(getActivity(), Permission.Group.STORAGE)) {
                        downloadFile(fileInfo);
                    }else{
                        checkStorePermission();
                    }
                }
            }
        });

        questionAndAnswersAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                FileInfo fileInfo = (FileInfo) baseQuickAdapter.getData().get(i);
                if (FileUtil.isFileExists(fileInfo.getName())) {
                    FileUtil.openFile(getActivity(),fileInfo);
                }else{
                    downloadFile(fileInfo);
                }
            }
        });


    }


    /**
     * 下载文件
     * @param fileInfo
     */
    private void downloadFile(final FileInfo fileInfo) {
        if (FileUtil.isFileExists(fileInfo.getName())) {
            return;
        }
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("正在下载"+fileInfo.getName());
        progressDialog.show();
        downloadCall = resourceApi.download(fileInfo.getId());
        downloadCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    FileUtil.saveFile(response.body(),fileInfo);
                    questionAndAnswersAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.error(getString(R.string.file_download_failure));
                }
                if (!getActivity().isFinishing() && progressDialog != null) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (!getActivity().isFinishing() && progressDialog != null) {
                    ToastUtils.error(getString(R.string.file_download_failure));
                    progressDialog.dismiss();
                }
            }
        });
    }

    /**
     * 检查存储权限
     */
    private void checkStorePermission() {
        addDisposable(PermissionUtil.checkStorePermission(getActivity()).subscribe(storeConsumer));
    }

    private Consumer storeConsumer = new Consumer<Boolean>() {
        @Override
        public void accept(Boolean aBoolean) throws Exception {
            if (!aBoolean) {
                checkStorePermission();
            }
        }
    };

    @Override
    public void onDestroy() {
        if (downloadCall != null) {
            downloadCall.cancel();
        }
        super.onDestroy();
    }
}
